摘要|Using Apollo with TypeScript

typescript 需要额外定义类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import React from "react";
import gql from "graphql-tag";
import { graphql } from "react-apollo";

const HERO_QUERY = gql`
query GetCharacter($episode: Episode!) {
hero(episode: $episode) {
name
id
friends {
name
id
appearsIn
}
}
}
`;
//类型
type Hero = {
name: string;
id: string;
appearsIn: string[];
friends: Hero[];
};
//查询结果的类型
type Response = {
hero: Hero;
};

const withCharacter = graphql<Response>(HERO_QUERY, {
options: () => ({
variables: { episode: "JEDI" }
})
});

export default withCharacter(({ data: { loading, hero, error } }) => {
if (loading) return <div>Loading</div>;
if (error) return <h1>ERROR</h1>;
return ...// actual component with data;
});

对于查询参数也需要定义类型

1
2
3
4
5
6
7
8
9
type InputProps = {
episode: string
};

const withCharacter = graphql<Response, InputProps>(HERO_QUERY, {
options: ({ episode }) => ({
variables: { episode }
}),
});

在包装组件获取 props 时也需要定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import React from "react";
import gql from "graphql-tag";
import { graphql, NamedProps, QueryProps} from "react-apollo";

const HERO_QUERY = gql`
query GetCharacter($episode: Episode!) {
hero(episode: $episode) {
name
id
friends {
name
id
appearsIn
}
}
}
`;

type Hero = {
name: string;
id: string;
appearsIn: string[];
friends: Hero[];
};

type Response = {
hero: Hero;
};

type WrappedProps = Response & QueryProps;

type InputProps = {
episode: string
};

const withCharacter = graphql<Response, InputProps, WrappedProps>(HERO_QUERY, {
options: ({ episode }) => ({
variables: { episode }
}),
props: ({ data }) => ({ ...data })
});

export default withCharacter(({ loading, hero, error }) => {
if (loading) return <div>Loading</div>;
if (error) return <h1>ERROR</h1>;
return ...// actual component with data;
});

使用class组件定义